<?php
namespace Warehouse\Model;

use Inbound\Model\CommoninterfaceModel;
use Inbound\Service\PrepareneedsService;

class BalanceModel extends CommoninterfaceModel{
    //数据库对象
    public $balance = null;
    //收货明细表
    static $table = 'balance';


    /**
     * @param string $table
     * @param array  $param
     */
    public function __construct($table = '', $param = array()) {
        $this->balance = M(self::$table, 'wms_', $this->_db);
        parent::__construct();
    }

    /**
     * 描述：获取某月的期初成本
     * 作者：橙子
     */
    public function get_inventory_cost($where = array()) {
        $_where = array();

        $inventory_date = date('Y-m-01', strtotime('-1 month'));

        if ($where['warehouse_date']) {
            $inventory_date = date('Y-m-01', strtotime($where['warehouse_date']));

        }

        $where['sku'] && $_where['sku'] = $where['sku'];
        $where['enterprise_dominant'] && $_where['enterprise_dominant'] = $where['enterprise_dominant'];
        $_where['inventory_date'] = $inventory_date;

        $result = $this->balance->field('sku,enterprise_dominant,sku_name,
        SUM(quantity) AS totalQuantity,SUM(cost) AS totalCost')
            ->group('sku,enterprise_dominant')
            ->where($_where)
            ->select();

        return empty($result) ? array() : $result;
    }

    /**
     * 描述：获取某月的期末成本
     * 作者：橙子
     */
    public function get_inventory_cost_end($where = array()) {
        $_where = array();

        $inventory_date = date('Y-m-01', strtotime('-1 month'));

        if ($where['warehouse_date']) {
            $inventory_date = date('Y-m-01', strtotime($where['warehouse_date']));
            $where['sku'] && $_where['sku'] = $where['sku'];
            $where['enterprise_dominant'] && $_where['enterprise_dominant'] = $where['enterprise_dominant'];

        }

        $inventory_date_end = date('Y-m-01', strtotime("{$inventory_date} + 1 month"));
        $_where['inventory_date'] = $inventory_date_end;

        $result = $this->balance->field('sku,enterprise_dominant,sku_name,
        SUM(quantity) AS totalQuantity,SUM(cost) AS totalCost')
            ->group('sku,enterprise_dominant')
            ->where($_where)
            ->select();

        return empty($result) ? array() : $result;
    }

    public function delete_inventories() {
        $model = $this->balance;
        $starttime = date('Y-m-01');

        $sql_de = "DELETE FROM `wms_balance` WHERE `inventory_date`='" . $starttime . "'";
        $model->execute($sql_de);
    }

    public function addall_data(&$data = array()) {
        $model = $this->balance;

        return $this->balance = $model->addAll($data);
    }
}